{% extends "base/base.html" %}

{% block title %}客户管理 - 项目合作归属数据管理系统{% endblock %}

{% block content %}
<div class="row">
    <div class="col-12">
        <h2><i class="bi bi-people"></i> 客户管理</h2>
        <p class="text-muted">管理所有客户信息，包括合作状态、项目分配等</p>
    </div>
</div>

<!-- 搜索表单 -->
<div class="search-form">
    <form method="GET" class="row g-3">
        <div class="col-md-3">
            <label class="form-label">客户姓名</label>
            <input type="text" class="form-control" name="search_name" value="{{ search_name }}" placeholder="请输入客户姓名">
        </div>
        <div class="col-md-3">
            <label class="form-label">项目序号</label>
            <select class="form-select" name="search_project">
                <option value="">全部项目</option>
                {% for project in project_numbers %}
                <option value="{{ project }}" {% if search_project == project %}selected{% endif %}>{{ project }}</option>
                {% endfor %}
            </select>
        </div>
        <div class="col-md-3">
            <label class="form-label">是否结束合作</label>
            <select class="form-select" name="search_cooperation_ended">
                <option value="">全部状态</option>
                <option value="false" {% if search_cooperation_ended == 'false' %}selected{% endif %}>合作中</option>
                <option value="true" {% if search_cooperation_ended == 'true' %}selected{% endif %}>已结束</option>
            </select>
        </div>
        <div class="col-md-3 d-flex align-items-end">
            <button type="submit" class="btn btn-primary me-2">
                <i class="bi bi-search"></i> 搜索
            </button>
            <a href="{{ url_for('customer.customer_management') }}" class="btn btn-outline-secondary">
                <i class="bi bi-arrow-clockwise"></i> 重置
            </a>
        </div>
    </form>
</div>

<!-- 操作工具栏 -->
<div class="row mb-3">
    <div class="col-12">
        <div class="d-flex justify-content-between align-items-center">
            <div>
                <button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#addCustomerModal">
                    <i class="bi bi-plus-circle"></i> 添加客户
                </button>
                <button type="button" class="btn btn-danger batch-operation-btn" onclick="batchDelete()" disabled>
                    <i class="bi bi-trash"></i> 批量删除
                </button>
            </div>
            <div>
                <a href="{{ url_for('customer.export_customers') }}" class="btn btn-outline-primary">
                    <i class="bi bi-download"></i> 导出数据
                </a>
            </div>
        </div>
    </div>
</div>

<!-- 客户列表 -->
<div class="card">
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover mb-0 data-table">
                <thead>
                    <tr>
                        <th width="40">
                            <input type="checkbox" class="form-check-input" id="selectAllCheckbox" onchange="toggleSelectAll(this)">
                        </th>
                        <th>客户姓名</th>
                        <th>项目序号</th>
                        <th>性别</th>
                        <th>合作开始时间</th>
                        <th>合作结束时间</th>
                        <th>合作天数</th>
                        <th>适宜项目负责人</th>
                        <th>合作状态</th>
                        <th width="150">操作</th>
                    </tr>
                </thead>
                <tbody>
                    {% for customer in customers.items %}
                    <tr>
                        <td>
                            <input type="checkbox" class="form-check-input" name="selected_items" value="{{ customer.id }}" onchange="updateBatchButtons()">
                        </td>
                        <td>{{ customer.name }}</td>
                        <td>{{ customer.project_number }}</td>
                        <td>{{ customer.gender or '-' }}</td>
                        <td>{{ customer.start_date.strftime('%Y-%m-%d') if customer.start_date else '-' }}</td>
                        <td>{{ customer.end_date.strftime('%Y-%m-%d') if customer.end_date else '-' }}</td>
                        <td>{{ customer.cooperation_days or '-' }}</td>
                        <td>{{ customer.suitable_manager or '-' }}</td>
                        <td>
                            {% if customer.is_cooperation_ended %}
                                <span class="badge bg-secondary">已结束</span>
                            {% else %}
                                <span class="badge bg-success">合作中</span>
                            {% endif %}
                        </td>
                        <td>
                            <div class="btn-group btn-group-sm">
                                <button type="button" class="btn btn-outline-primary" 
                                        onclick="editCustomer({{ customer.id }})" 
                                        data-bs-toggle="modal" 
                                        data-bs-target="#editCustomerModal">
                                    <i class="bi bi-pencil"></i>
                                </button>
                                <button type="button" class="btn btn-outline-danger" 
                                        onclick="deleteCustomer({{ customer.id }})">
                                    <i class="bi bi-trash"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- 分页 -->
{% if customers.pages > 1 %}
<nav class="mt-4">
    <ul class="pagination justify-content-center">
        {% if customers.has_prev %}
        <li class="page-item">
            <a class="page-link" href="{{ url_for('customer.customer_management', page=customers.prev_num, search_name=search_name, search_project=search_project, search_cooperation_ended=search_cooperation_ended) }}">上一页</a>
        </li>
        {% endif %}
        
        {% for page_num in customers.iter_pages() %}
            {% if page_num %}
                {% if page_num != customers.page %}
                <li class="page-item">
                    <a class="page-link" href="{{ url_for('customer.customer_management', page=page_num, search_name=search_name, search_project=search_project, search_cooperation_ended=search_cooperation_ended) }}">{{ page_num }}</a>
                </li>
                {% else %}
                <li class="page-item active">
                    <span class="page-link">{{ page_num }}</span>
                </li>
                {% endif %}
            {% else %}
                <li class="page-item disabled">
                    <span class="page-link">…</span>
                </li>
            {% endif %}
        {% endfor %}
        
        {% if customers.has_next %}
        <li class="page-item">
            <a class="page-link" href="{{ url_for('customer.customer_management', page=customers.next_num, search_name=search_name, search_project=search_project, search_cooperation_ended=search_cooperation_ended) }}">下一页</a>
        </li>
        {% endif %}
    </ul>
</nav>
{% endif %}

<!-- 添加客户模态框 -->
<div class="modal fade" id="addCustomerModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">添加客户</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" action="{{ url_for('customer.add_customer') }}" data-validate="true">
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">客户姓名 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="name" required placeholder="请输入客户姓名（可中文、数字、英文）">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">项目序号 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="project_number" required placeholder="请输入项目序号">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">性别</label>
                            <select class="form-select" name="gender">
                                <option value="">请选择性别</option>
                                <option value="男">男</option>
                                <option value="女">女</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">适宜项目负责人</label>
                            <select class="form-select" name="suitable_manager">
                                <option value="">请选择项目负责人</option>
                                {% for manager in suitable_managers %}
                                <option value="{{ manager }}">{{ manager }}</option>
                                {% endfor %}
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">合作开始时间</label>
                            <input type="date" class="form-control" name="start_date">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">合作结束时间</label>
                            <input type="date" class="form-control" name="end_date">
                        </div>
                        <div class="col-12">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="is_cooperation_ended">
                                <label class="form-check-label">
                                    已结束合作
                                </label>
                            </div>
                        </div>
                        <div class="col-12">
                            <label class="form-label">备注信息</label>
                            <textarea class="form-control" name="notes" rows="3" placeholder="请输入备注信息（可选）"></textarea>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-success">保存</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 编辑客户模态框 -->
<div class="modal fade" id="editCustomerModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">编辑客户</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" id="editCustomerForm" data-validate="true">
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">客户姓名 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="name" id="edit_name" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">项目序号 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="project_number" id="edit_project_number" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">性别</label>
                            <select class="form-select" name="gender" id="edit_gender">
                                <option value="">请选择性别</option>
                                <option value="男">男</option>
                                <option value="女">女</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">适宜项目负责人</label>
                            <select class="form-select" name="suitable_manager" id="edit_suitable_manager">
                                <option value="">请选择项目负责人</option>
                                {% for manager in suitable_managers %}
                                <option value="{{ manager }}">{{ manager }}</option>
                                {% endfor %}
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">合作开始时间</label>
                            <input type="date" class="form-control" name="start_date" id="edit_start_date">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">合作结束时间</label>
                            <input type="date" class="form-control" name="end_date" id="edit_end_date">
                        </div>
                        <div class="col-12">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="is_cooperation_ended" id="edit_is_cooperation_ended">
                                <label class="form-check-label">
                                    已结束合作
                                </label>
                            </div>
                        </div>
                        <div class="col-12">
                            <label class="form-label">备注信息</label>
                            <textarea class="form-control" name="notes" id="edit_notes" rows="3"></textarea>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">更新</button>
                </div>
            </form>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
// 确保函数在页面中可用
function toggleSelectAll(checkbox) {
    console.log('toggleSelectAll called');
    const checkboxes = document.querySelectorAll('input[type="checkbox"][name="selected_items"]');
    console.log('Found checkboxes:', checkboxes.length);
    
    checkboxes.forEach(cb => {
        cb.checked = checkbox.checked;
    });
    
    updateBatchButtons();
}

function updateBatchButtons() {
    console.log('updateBatchButtons called');
    const checkedBoxes = document.querySelectorAll('input[type="checkbox"][name="selected_items"]:checked');
    const batchButtons = document.querySelectorAll('.batch-operation-btn');
    
    console.log('Checked boxes:', checkedBoxes.length, 'Batch buttons:', batchButtons.length);
    
    batchButtons.forEach(btn => {
        console.log('Updating button, disabled:', checkedBoxes.length === 0);
        btn.disabled = checkedBoxes.length === 0;
    });
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM loaded, initializing...');
    updateBatchButtons();
});

// 编辑客户
function editCustomer(customerId) {
    // 获取客户数据（这里简化处理，实际应该通过AJAX获取）
    const row = document.querySelector(`input[value="${customerId}"]`).closest('tr');
    const cells = row.cells;
    
    document.getElementById('edit_name').value = cells[1].textContent;
    document.getElementById('edit_project_number').value = cells[2].textContent;
    document.getElementById('edit_gender').value = cells[3].textContent === '-' ? '' : cells[3].textContent;
    document.getElementById('edit_start_date').value = cells[4].textContent === '-' ? '' : cells[4].textContent;
    document.getElementById('edit_end_date').value = cells[5].textContent === '-' ? '' : cells[5].textContent;
    document.getElementById('edit_is_cooperation_ended').checked = cells[8].textContent.includes('已结束');
    
    // 设置表单action
    document.getElementById('editCustomerForm').action = `/customer/edit/${customerId}`;
}

// 删除客户
function deleteCustomer(customerId) {
    if (confirm('确定要删除这个客户吗？此操作不可撤销。')) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = `/customer/delete/${customerId}`;
        document.body.appendChild(form);
        form.submit();
    }
}

// 批量删除
function batchDelete() {
    const selected = document.querySelectorAll('input[name="selected_items"]:checked');
    if (selected.length === 0) {
        alert('请选择要删除的客户');
        return;
    }
    
    if (confirm(`确定要删除选中的 ${selected.length} 个客户吗？此操作不可撤销。`)) {
        selected.forEach(checkbox => {
            deleteCustomer(checkbox.value);
        });
    }
}
</script>
{% endblock %}

